<template>
	<view class="boxCav">
		<view class="navBox">
			<topStatus></topStatus>
			<view class="nav_main">
					<uni-icons type="left" color="#343434" size="30" @click="goBack()"></uni-icons>
					<view class="nav_tit">
						
					</view>
					<uni-icons type="left" color="#333" size="30" style="opacity: 0;"></uni-icons>
			</view>
		</view>
		<canvas
			canvas-id="hoCanvas"
			class="hoCanvas"
			v-if="canvasHeight"
			:style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
		></canvas>
		<cover-view class="saveBtn" v-if="showSave" @click="saveImg()">保存到相册</cover-view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			canvasWidth: 375,
			canvasHeight: 0,

			logo: 'https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/1723617981177445.png',
			bgSrc: 'https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/1732525054445200.png',
			bgWidth: '',
			bgHeight: '',
			bgRatio: '',

			qrSrc: '',
			qrWidth: 188,
			qrHeight: 188,

			headSrc: '',
			headWidth: 76,
			headHeight: 76,

			userName: '用户昵称',

			qr: {},
			postUrl: '',
			Data: {},
			showSave: false,
			errText:''
		};
	},
	onLoad() {},
	created() {
		uni.showLoading({
			title: '海报正在生成...',
			icon: 'loading',
		});
		this.Data = this.$store.state.shopCanvas;
		// this.Data.ProductName = this.Data.ProductName.length > 12 ? this.Data.ProductName.slice(0, 12) + '...' : this.Data.ProductName
		this.Data.ProductName = this.truncateText(this.Data.ProductName, 12, 2);
		this.Data.Images = this.ImgSplitFun(this.Data.Images)
	},
	async mounted() {
		// await this.getUserInfo()
		// await this.CreateShareQR()
		await this.getHead();
		await this.getQR();

		this.drawFun();
	},

	methods: {
		goBack() {
			const pages = getCurrentPages();
			if (pages.length > 1) {
				// 如果页面栈长度大于1，则说明有上一页，可以返回
				uni.navigateBack();
			} else {
				// 如果没有上一页，则导航到首页
				uni.reLaunch({
						url: '/pages/tab/home'
				});
			}
		},
		truncateText(text, charsPerLine, maxLines) {
			console.log(text,'texttexttext');
			
			// 分割成每行charsPerLine个字符
			const lines = text.match(new RegExp('.{1,' + charsPerLine + '}', 'g')) || [];

			// 只保留maxLines行
			const truncatedLines = lines.slice(0, maxLines);

			// 如果原始文本的行数超过了maxLines，最后添加省略号
			if (lines.length > maxLines) {
				truncatedLines[maxLines - 1] += '...';
			}

			// 将截取后的行连接成一个字符串
			return truncatedLines;
		},
		async getUserInfo() {
			let u = uni.getStorageSync('user');
			let res = await this.$api.post('User/GetUserInfo', {
				ID: u.UserID,
			});
			this.user = res.data;
		},
		async CreateShareQR() {
			let res = await this.$api.post('Action/CreateShareQR', {
				Page: 'pages/tab/home',
				scene: uni.getStorageSync('user').ID,
			});
			this.qr = res.data;
		},
		ImgSplitFun(img){
			if(img){
				return img.split(',')[0]
			}
			return img
		},
		getHead() {
			return new Promise((resolve, reject) => {
				this.headSrc = this.Data.HeadImgUrl;
				// this.headSrc = 'https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/171549434162266.jpg'
				resolve(this.headSrc);
			});
		},
		getQR() {
			return new Promise((resolve, reject) => {
				setTimeout(() => {
					this.qrSrc = this.Data.Qr;
					// this.qrSrc = 'https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/1724925186646988.png'
					resolve(this.qrSrc);
				}, 1000);
			});
		},

		//绘制头像
		headDraw(ctx, src, headW, headH) {
			let top = 210;
			let left = 42;
			let width = 50;
			let height = 50;

			const R = width / 2;
			const centerX = left + R;
			const centerY = top + R;
			//头像中心坐标
			const headX = headW / 2;
			const headY = headH / 2;
			let sx = 0,
				sy = 0,
				sWidth = headW,
				sHeight = headH;
			//横图
			if (headW > headH) {
				sWidth = headH;
				sy = 0;
				sx = headX - sWidth / 2;
			} else {
				sHeight = headW;
				sx = 0;
				sy = headY - sHeight / 2;
			}

			// let avaImg_w,avaImg_h
			// let rat = headW / headH
			// let rCri = 55	//头像直径
			// if (headW <= headH) {
			// 	avaImg_w = rCri
			// 	avaImg_h = rCri/rat
			// }else{
			// 	avaImg_h = rCri
			// 	avaImg_w = rCri*rat
			// }

			ctx.save(); // 保存当前的绘图上下文
			ctx.arc(centerX, centerY, R, 0, Math.PI * 2);
			ctx.clip();
			ctx.drawImage(src, sx, sy, sWidth, sHeight, left, top, width, height);
			ctx.restore();
		},
		shopImgDraw(ctx, src, headW, headH) {
			const radius = 12; // 圆角半径
			const width = 290; // 目标宽度
			const height = 290; // 目标高度
			let top = 271;
			let left = 42;

			const R = width / 2;
			const centerX = left + R;
			const centerY = top + R;
			//头像中心坐标
			const headX = headW / 2;
			const headY = headH / 2;
			let sx = 0,
				sy = 0,
				sWidth = headW,
				sHeight = headH;
			//横图
			if (headW > headH) {
				sWidth = headH;
				sy = 0;
				sx = headX - sWidth / 2;
			} else {
				sHeight = headW;
				sx = 0;
				sy = headY - sHeight / 2;
			}

			// 开始绘制路径
			ctx.beginPath();
			ctx.moveTo(left + radius, top);
			ctx.lineTo(left + width - radius, top);
			ctx.arcTo(left + width, top, left + width, top + radius, radius);
			ctx.lineTo(left + width, top + height - radius);
			ctx.arcTo(left + width, top + height, left + width - radius, top + height, radius);
			ctx.lineTo(left + radius, top + height);
			ctx.arcTo(left, top + height, left, top + height - radius, radius);
			ctx.lineTo(left, top + radius);
			ctx.arcTo(left, top, left + radius, top, radius);
			ctx.closePath();

			ctx.clip();

			ctx.drawImage(src, sx, sy, sWidth, sHeight, left, top, width, height);
			// ctx.restore();
		},
		//二维码部分
		QrDraw(ctx, qr) {
			// ctx.textAlign = 'center'
			ctx.font = 'bold 14px PingFang-SC';
			ctx.setFillStyle('#999');
			ctx.fillText(this.Data.Name, 100, 226);

			ctx.setFillStyle('#333');
			ctx.fillText('分享了一份好礼给您！', 100, 250);

			ctx.font = 'bold 14px PingFang-SC';
			ctx.setFillStyle('#333');
			ctx.fillText('分享了一份好礼给您！', 100, 250);

			//价格
			if(!this.Data.Promotion){
				ctx.font = 'bold 19px PingFang-SC';
				ctx.setFillStyle('#F9371C');
				ctx.fillText('￥' + this.Data.Price, 42, 590);
			}else{
		// 		const tagPadding = 4
		// 		const tagWidth = ctx.measureText(this.Data.PromotionType).width + tagPadding * 2;
		// 		const tagHeight = 12 + tagPadding;
				
		// 		ctx.setStrokeStyle('#E60012'); // 红色边框
		// 		ctx.setLineWidth(1);
		// 		ctx.strokeRect(42, 590 - tagHeight / 2, tagWidth, tagHeight); // 画矩形边框
		
		// 		ctx.font = '500 12px PingFang-SC';
		// 		ctx.setFillStyle('#E60012'); // 文本颜色
		// 		ctx.fillText(this.Data.PromotionType, 42 + tagPadding, 590 + 12 / 2 - 2); // 填充文字
				
		// 		ctx.font = 'bold 19px PingFang-SC';
		// 		ctx.setFillStyle('#F9371C');
		// 		ctx.fillText('￥' + this.Data.Price, 42 + tagWidth + 10, 590 + 19 / 3);
				
				
				
				ctx.font = '500 14px PingFang-SC';
				ctx.setFillStyle('#F9371C');
				ctx.fillText(this.Data.PromotionType, 44, 590);
				const PromotionTypeWidth = ctx.measureText(this.Data.PromotionType)
				
				ctx.font = '500 19px PingFang-SC';
				ctx.setFillStyle('#F9371C');
				ctx.fillText('￥'+this.Data.Promotion, 44 + PromotionTypeWidth.width+1, 590);
				const PromotionWidth = ctx.measureText('￥'+this.Data.Promotion)
				
				const oldPriceX = 44 +  PromotionTypeWidth.width+PromotionWidth.width + 6;
				ctx.font = '500 14px PingFang-SC';
				ctx.setFillStyle('#999'); // 灰色原价
				ctx.fillText('￥'+this.Data.Price, oldPriceX, 590);
				
				const oldPriceWidth = ctx.measureText('￥'+this.Data.Price).width + 2;
				const lineY = 590 - 5;
				ctx.setStrokeStyle('#999');
				ctx.setLineWidth(1);
				ctx.moveTo(oldPriceX, lineY);
				ctx.lineTo(oldPriceX + oldPriceWidth, lineY);
				ctx.stroke();
				
			}
			

			//商品标题
			ctx.font = 'bold 16px PingFang-SC';
			ctx.setFillStyle('#333');
			ctx.fillText(this.Data.ProductName[0], 45, 615);

			if (this.Data.ProductName.length == 2) {
				ctx.font = 'bold 16px PingFang-SC';
				ctx.setFillStyle('#333');
				ctx.fillText(this.Data.ProductName[1], 45, 635);
			}
			this.drawLconic(ctx,45,615)
			
			
			ctx.font = '500 12px PingFang-SC';
			ctx.setFillStyle('#999');
			ctx.fillText('长按识别查看', 257, 662);

			//二维码
			ctx.drawImage(qr, 261, 581, 66, 66);
		},
		drawLconic(ctx,xWidth,yHeight){
			if(!this.Data.PGI_ProductName){
				return
			}
			
			if (this.Data.ProductName.length == 2) {
				ctx.font = '500 14px PingFang-SC';
				ctx.setFillStyle('#03A9F4');
				ctx.fillText('地理标志产品', xWidth, yHeight + 20 + 20);
			}else{
				ctx.fillText('地理标志产品', xWidth, yHeight + 20);
			}
		},
		drawFun() {
			const that = this;
			//背景
			let promiseBg = new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: that.bgSrc,
					success: (res) => {
						that.bgWidth = res.width;
						that.bgHeight = res.height;
						that.bgRatio = res.width / res.height;
						resolve(res);
					},
					fail: (err) => {
						console.log('promiseBg错误');
						this.errText = 'CreateBackground is Error'
						this.$pv.msg('[Error]CreateBackground is Error');
						reject(err);
					},
				});
			});
			//二维码
			let promiseQR = new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: that.qrSrc,
					success: (res) => {
						resolve(res);
					},
					fail: (err) => {
						console.log('promiseQR错误');
						this.errText = 'CreateShareQR is Error'
						this.$pv.msg('[Error]CreateShareQR is Error');
						reject(err);
					},
				});
			});

			let promiseShopImg = new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: that.ImgSplitFun(that.Data.Images),
					success: (res) => {
						resolve(res);
					},
					fail: (err) => {
						console.log('shopimg错误');
						this.errText = 'ShopImg is Error'
						this.$pv.msg('[Error]ShopImg is Error');
						reject(err);
					},
				});
			});
			//头像
			let promiseHead = new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: that.headSrc,
					success: (res) => {
						resolve(res);
					},
					fail: (err) => {
						console.log('promiseHead错误');
						this.errText = 'HeadImgUrl is Error'
						this.$pv.msg('[Error]HeadImgUrl is Error');
						reject(err);
					},
				});
			});

			setTimeout(() => {
				const query = uni.createSelectorQuery();
				//指定要获取的属性，这里设置为size: true表示要获取尺寸信息。
				query
					.select('.hoCanvas')
					.fields({ node: true, size: true }, (res) => {
						that.canvasWidth = 375;
						that.canvasHeight = that.canvasWidth / that.bgRatio;
						console.log(that.canvasHeight,'11111');
						
						Promise.all([promiseBg, promiseQR, promiseHead, promiseShopImg])
							.then((rex) => {
								console.log('----------', rex);

								const ctx = uni.createCanvasContext('hoCanvas', this);
								// ctx.canvasWidth = this.canvasWidth; // 背景图片的实际宽度
								// ctx.canvasHeight = this.canvasHeight ;
								//绘制背景
								ctx.drawImage(rex[0].path, 0, 0, that.canvasWidth, that.canvasHeight);

								//绘制头像
								that.headDraw(ctx, rex[2].path, rex[2].width, rex[2].height);

								this.QrDraw(ctx, rex[1].path);
								that.shopImgDraw(ctx, rex[3].path, rex[3].width, rex[3].height);

								ctx.draw();

								setTimeout(() => {
									uni.canvasToTempFilePath(
										{
											x: 0,
											y: 0,
											width: that.canvasWidth,
											height: that.canvasHeight,
											destWidth: that.canvasWidth * 2,
											destHeight: that.canvasHeight * 2,
											canvasId: 'hoCanvas',
											success: function (res) {
												that.postUrl = res.tempFilePath;
												// that.saveImg();
												that.showSave = true;
												// that.$emit('showSaveFun',true)
												if (that.postUrl) {
													uni.hideLoading();
													// that.$emit('getCanvasImg',res.tempFilePath)
												}
											},
											fail: function (err) {
												console.log(err);
											},
										},
										this
									);
								}, 500);
							})
							.catch((err) => {
								uni.hideLoading();
								uni.showModal({
									title: '异常错误',
									content:`图片生成失败!!!\n[Error:${this.errText}]`,
									showCancel: false,
									success: (res) => {
										if (res.confirm) uni.navigateBack();
									},
								});
							});
					})
					.exec();
			}, 1000);
		},
		saveImg() {
			const that = this;
			//将图片保存到相册
			uni.saveImageToPhotosAlbum({
				filePath: that.postUrl,
				success(res) {
					uni.showModal({
						title: '保存成功',
						content: '图片成功保存到相册了，快去分享朋友圈吧',
						showCancel: false,
						confirmText: '好的',
						success: function (res) {
							if (res.confirm) {
							}
							// that.hideShareImg()
						},
					});
				},
				fail(err) {
					console.log(err);
				},
			});
			console.log('保存');
		},
	},
};
</script>

<style lang="scss">
page {
	background: linear-gradient(141deg, #fe0137 0%, #f9555f 24%, #fa716e 71%, #ffc596 100%);
}

.navBox {
	width: 100%;
	position: fixed;
	top: 0;
	left: 0;
	z-index: 10;

	.nav_main {
			padding: 0 14rpx;
			height: 44px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 36rpx;
			color: #fff;

			.nav_tit {
					font-weight: bold;
					font-size: 36rpx;
					color: #333333;
			}
	}
}
.boxCav {
	padding-bottom: 150rpx;
}
.hoCanvas {
	width: 350px;
	height: 650px;
	border-radius: 8rpx;
	overflow: hidden;
	margin: 20rpx auto;
	z-index: 1;
}
.saveBtn {
	position: fixed;
	bottom: 10rpx;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 90%;
	height: 96rpx;
	text-align: center;
	line-height: 96rpx;
	background: #ffffff;
	border-radius: 8px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: bold;
	font-size: 16px;
	color: #5d8bf8;
	z-index: 999999;
}
</style>
